package com.example.beixiangsuapp.bxs.utils;

import android.Manifest;
import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import android.widget.Toast;


import java.io.ByteArrayOutputStream;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Enumeration;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import okhttp3.Headers;
import okhttp3.Response;

public class CommonUtils {
    private static final String TAG = "Commonutils";
    private static DecimalFormat df = new DecimalFormat("###.0000");
    private static Handler handler=new Handler(Looper.getMainLooper());
    public static String sessionid;

    //获取handler实例
    public static Handler getHandler() {
        return handler;
    }
    //3.在主线程执行任务
    public static void runOnUIThrad(Runnable task){
        handler.post(task);
    }
    //在子线程中执行任务
    //格式化小数
    public static String forMatNum(Object num){
        return df.format(num);
    }
    //4.在主线程里面吐司

    public static void showToast(final Context context, final String text) {
        final Toast toast = Toast.makeText(context, text, Toast.LENGTH_SHORT);
        final Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                toast.show();
            }
        }, 0, 3000);
        new Timer().schedule(new TimerTask() {
            @Override
            public void run() {
                toast.cancel();
                timer.cancel();
            }
        }, 1500);

    }

    /**
     * 获取当月的最大天数
     * */
    public static int getCurrentMonthDay() {
        Calendar a = Calendar.getInstance();
        a.set(Calendar.DATE, 1);
        a.roll(Calendar.DATE, -1);
        int maxDate = a.get(Calendar.DATE);
        return maxDate;
    }

    /**
     * 获取当前的年月日等时间
     */
    public static int getCurrentDate(String key){
        Calendar c = Calendar.getInstance();
        // 取得系统日期:
        int year = c.get(Calendar.YEAR);
        int month = c.get(Calendar.MONTH) + 1;
        int day = c.get(Calendar.DAY_OF_MONTH);
        // 取得系统时间：
        int hour = c.get(Calendar.HOUR_OF_DAY);
        int minute = c.get(Calendar.MINUTE);
//		System.out.println(year + "年" + month + "月" + day + "日" + hour
//				+ "时" + minute + "分" );
        if ("year".equalsIgnoreCase(key)) {
            return year;
        }
        if ("month".equalsIgnoreCase(key)) {
            return month;
        }
        if ("day".equalsIgnoreCase(key)) {
            return month;
        }
        if ("hour".equalsIgnoreCase(key)) {
            return month;
        }
        if ("minute".equalsIgnoreCase(key)) {
            return month;
        }
        return -1;
    }

    /**
     * 初始化Cookies
     * @param response
     */
    public static void initCookie(Response response){
        Headers headers = response.headers();
        for (int j = 0; j < headers.size(); j++) {
            //  Log.d(TAG, "headers: "+headers.name(j)+"----值是"+headers.values(headers.name(j)));
            if ("Set-Cookie".equals(headers.name(j))){
                String value = headers.value(j);
                value = value.substring(value.indexOf("=")+1,value.indexOf("; P"));
                Log.d(TAG, "onResponse: 这是sessionID:   "+value);
                sessionid =  value;
                break;
            }
        }
    }

    /**
     *  进一法获取小数点两位的数
     */
    public  static String   intoALaw(String string){
        try {

            double parseDouble = Double.parseDouble(string);
            parseDouble=parseDouble+0.009;
            String parseStr=parseDouble+"";
            int indexOf = parseStr.indexOf('.');
            String substring = parseStr.substring(0, indexOf + 3);
            Log.e("intoALaw",substring);
            return substring;
        }catch (NumberFormatException e){
            Log.e("CommUtils","intoALaw");
            return null;
        }

    }



    /**
     * 判断手机号码是否输入正确;
     * @param phone
     * @return
     */
    public static boolean checkPhone(String phone) {
        Pattern pattern = Pattern
                .compile("^((1[0-9][0-9]))\\d{8}$");
        Matcher matcher = pattern.matcher(phone);

        if (matcher.matches()) {
            return true;
        }
        return false;
    }

    public static String getLocalIpAddress() throws SocketException {
        for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();)
        {
            NetworkInterface intf = en.nextElement();
            for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();)
            {
                InetAddress inetAddress = enumIpAddr.nextElement();
                if (!inetAddress.isLoopbackAddress())
                {
                    return inetAddress.getHostAddress().toString();
                }
            }
        }

        return null;
    }
    public static String bitmap2String(Bitmap bitmap)
    {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();// outputstream
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        byte[] appicon = baos.toByteArray();// 转为byte数组
        return Base64.encodeToString(appicon, Base64.DEFAULT);

    }
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }
    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }


    //获取mac地址
    // 有兴趣的朋友可以看下NetworkInterface在Android FrameWork中怎么实现的
    public static String macAddress() throws SocketException {
        String address = null;
        // 把当前机器上的访问网络接口的存入 Enumeration集合中
        Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
        while (interfaces.hasMoreElements()) {
            NetworkInterface netWork = interfaces.nextElement();
            // 如果存在硬件地址并可以使用给定的当前权限访问，则返回该硬件地址（通常是 MAC）。
            byte[] by = netWork.getHardwareAddress();
            if (by == null || by.length == 0) {
                continue;
            }
            StringBuilder builder = new StringBuilder();
            for (byte b : by) {
                builder.append(String.format("%02X:", b));
            }
            if (builder.length() > 0) {
                builder.deleteCharAt(builder.length() - 1);
            }
            String mac = builder.toString();
            Log.d("mac", "interfaceName="+netWork.getName()+", mac="+mac);
            // 从路由器上在线设备的MAC地址列表，可以印证设备Wifi的 name 是 wlan0
            if (netWork.getName().equals("wlan0")) {
                Log.d("mac", " interfaceName ="+netWork.getName()+", mac="+mac);
                address = mac;
            }
        }
        return address;
    }

    /**
     * 检查手机上是否安装了指定的软件
     *
     * @param context
     * @param packageName：应用包名
     * @return
     */
    public static boolean isAvilible(Context context, String packageName) {
        //获取packagemanager
        final PackageManager packageManager = context.getPackageManager();
        //获取所有已安装程序的包信息
        List<PackageInfo> packageInfos = packageManager.getInstalledPackages(0);
        //用于存储所有已安装程序的包名
        List<String> packageNames = new ArrayList<String>();
        //从pinfo中将包名字逐一取出，压入pName list中
        if (packageInfos != null) {
            for (int i = 0; i < packageInfos.size(); i++) {
                String packName = packageInfos.get(i).packageName;
                packageNames.add(packName);
            }
        }
        //判断packageNames中是否有目标程序的包名，有TRUE，没有FALSE
        return packageNames.contains(packageName);
    }

    /**
     * 判断日期格式是否输入正确;
     * @param birth
     * @return
     */
    public static boolean checkBirthDay(String birth) {
        Pattern pattern = Pattern
                .compile("^(19|20)\\d{2}-(1[0-2]|0?[1-9])-(0?[1-9]|[1-2][0-9]|3[0-1])$");
        Matcher matcher = pattern.matcher(birth);

        if (matcher.matches()) {
            return true;
        }
        return false;
    }
    /**
     * 判断shen是否输入正确;
     * @param birth
     * @return
     */
    public static boolean checkIdCard(String birth) {
        Pattern pattern = Pattern
                .compile("^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}([0-9]|X)$");
        Matcher matcher = pattern.matcher(birth);

        if (matcher.matches()) {
            return true;
        }
        return false;
    }

    public static String getVersionName(Context context) throws PackageManager.NameNotFoundException {
        PackageManager packageManager = context.getPackageManager();
        PackageInfo info = packageManager.getPackageInfo(context.getPackageName(), 0);
        return info.versionName;
    }
    /**
     * 判断某个界面是否在前台
     *
     * @param context
     * @param className
     *            某个界面名称
     */
    public static boolean isForeground(Context context, String className) {
        if (context == null || TextUtils.isEmpty(className)) {
            return false;
        }

        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> list = am.getRunningTasks(1);
        if (list != null && list.size() > 0) {
            ComponentName cpn = list.get(0).topActivity;
            if (className.equals(cpn.getClassName())) {
                return true;
            }
        }

        return false;
    }

    public static boolean checkNetworkInfo(Context context) {
        ConnectivityManager conMan = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo.State mobile = conMan.getNetworkInfo(ConnectivityManager.TYPE_MOBILE)
                .getState();
        NetworkInfo.State wifi = conMan.getNetworkInfo(ConnectivityManager.TYPE_WIFI)
                .getState();
        if (mobile == NetworkInfo.State.CONNECTED || mobile == NetworkInfo.State.CONNECTING)
            return true;
        if (wifi == NetworkInfo.State.CONNECTED || wifi == NetworkInfo.State.CONNECTING)
            return true;
        return false;


    }


}
